<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="协议编码" prop="agreementCode">
        <el-input
          v-model="queryParams.agreementCode"
          placeholder="请输入协议编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="协议类型" prop="agreementType">
        <el-select v-model="queryParams.agreementType" placeholder="请选择协议类型" clearable>
          <el-option
            v-for="dict in protocol_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合作方编码" prop="partnerCode" label-width="90px">
        <el-input
          v-model="queryParams.partnerCode"
          placeholder="请输入合作方编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['agreement:agreement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agreement:agreement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['agreement:agreement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['agreement:agreement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="agreementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="协议编码" align="center" prop="agreementCode" />
      <el-table-column label="协议类型" align="center" prop="agreementType">
        <template #default="scope">
          <dict-tag :options="protocol_type" :value="scope.row.agreementType"/>
        </template>
      </el-table-column>
      <el-table-column label="协议状态" align="center" prop="agreementStatus" />
      <el-table-column label="合作方编码" align="center" prop="partnerCode" />
      <el-table-column label="协议的详细内容" align="center" prop="agreementContent" />
      <el-table-column label="协议的创建日期" align="center" prop="creationDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.creationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="提成率" align="center" prop="commissionRate" />
      <el-table-column label="分红率" align="center" prop="bonusRate" />
      <el-table-column label="折扣率" align="center" prop="discountRate" />
      <el-table-column label="备注信息" align="center" prop="remark" />
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['agreement:agreement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['agreement:agreement:remove']">删除</el-button>
           <!-- 新增上传按钮 -->
    <el-upload
      class="upload-demo"
      :action="uploadUrl"
      :headers="headers"
      :data="{ agreementCode: scope.row.agreementCode }"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload"
      v-hasPermi="['agreement:agreement:upload']">
      <el-button link type="primary" icon="Upload">上传</el-button>
    </el-upload>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改结算协议对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="agreementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="协议类型" prop="agreementType">
          <el-select v-model="form.agreementType" placeholder="请选择协议类型">
            <el-option
              v-for="dict in protocol_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="form.partnerCode" placeholder="请输入合作方编码" />
        </el-form-item>
        <el-form-item label="协议的详细内容">
          <editor v-model="form.agreementContent" :min-height="192"/>
        </el-form-item>
        <el-form-item label="协议的创建日期" prop="creationDate">
          <el-date-picker clearable
            v-model="form.creationDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择协议的创建日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="协议的最后修改日期" prop="lastModifiedDate">
          <el-date-picker clearable
            v-model="form.lastModifiedDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择协议的最后修改日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="提成率" prop="commissionRate">
          <el-input v-model="form.commissionRate" placeholder="请输入提成率" />
        </el-form-item>
        <el-form-item label="分红率" prop="bonusRate">
          <el-input v-model="form.bonusRate" placeholder="请输入分红率" />
        </el-form-item>
        <el-form-item label="折扣率" prop="discountRate">
          <el-input v-model="form.discountRate" placeholder="请输入折扣率" />
        </el-form-item>
        <el-divider content-position="center">协议规则信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddAgreementRule">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteAgreementRule">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="agreementRuleList" :row-class-name="rowAgreementRuleIndex" @selection-change="handleAgreementRuleSelectionChange" ref="agreementRule">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="税率" prop="taxRate" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.taxRate" placeholder="请输入税率" />
            </template>
          </el-table-column>
          <el-table-column label="税额" prop="taxAmount" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.taxAmount" placeholder="请输入税额" />
            </template>
          </el-table-column>
          <el-table-column label="结算周期" prop="settlementCycle" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.settlementCycle" placeholder="请输入结算周期" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Agreement">
import { listAgreement, getAgreement, delAgreement, addAgreement, updateAgreement } from "@/api/settled/agreement";

const { proxy } = getCurrentInstance();
const { protocol_type } = proxy.useDict('protocol_type');

const agreementList = ref([]);
const agreementRuleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedAgreementRule = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agreementCode: null,
    agreementType: null,
    partnerCode: null,
  },
  rules: {
    agreementType: [
      { required: true, message: "协议类型不能为空", trigger: "change" }
    ],
    agreementStatus: [
      { required: true, message: "协议状态不能为空", trigger: "change" }
    ],
    agreementContent: [
      { required: true, message: "协议的详细内容不能为空", trigger: "blur" }
    ],
    creationDate: [
      { required: true, message: "协议的创建日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询结算协议列表 */
function getList() {
  loading.value = true;
  listAgreement(queryParams.value).then(response => {
    agreementList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    agreementCode: null,
    agreementType: null,
    agreementStatus: null,
    partnerCode: null,
    agreementContent: null,
    creationDate: null,
    lastModifiedDate: null,
    lastModifiedBy: null,
    remark: null,
    commissionRate: null,
    bonusRate: null,
    discountRate: null
  };
  agreementRuleList.value = [];
  proxy.resetForm("agreementRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.agreementCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加结算协议";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _agreementCode = row.agreementCode || ids.value
  getAgreement(_agreementCode).then(response => {
    form.value = response.data;
    agreementRuleList.value = response.data.agreementRuleList;
    open.value = true;
    title.value = "修改结算协议";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["agreementRef"].validate(valid => {
    if (valid) {
      form.value.agreementRuleList = agreementRuleList.value;
      if (form.value.agreementCode != null) {
        updateAgreement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAgreement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _agreementCodes = row.agreementCode || ids.value;
  proxy.$modal.confirm('是否确认删除结算协议编号为"' + _agreementCodes + '"的数据项？').then(function() {
    return delAgreement(_agreementCodes);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 协议规则序号 */
function rowAgreementRuleIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 协议规则添加按钮操作 */
function handleAddAgreementRule() {
  let obj = {};
  obj.agreementFormula = "";
  obj.taxRate = "";
  obj.taxAmount = "";
  obj.settlementCycle = "";
  obj.remark = "";
  agreementRuleList.value.push(obj);
}

/** 协议规则删除按钮操作 */
function handleDeleteAgreementRule() {
  if (checkedAgreementRule.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的协议规则数据");
  } else {
    const agreementRules = agreementRuleList.value;
    const checkedAgreementRules = checkedAgreementRule.value;
    agreementRuleList.value = agreementRules.filter(function(item) {
      return checkedAgreementRules.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleAgreementRuleSelectionChange(selection) {
  checkedAgreementRule.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('agreement/agreement/export', {
    ...queryParams.value
  }, `agreement_${new Date().getTime()}.xlsx`)
}

getList();
</script>
